﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace Hangout.Web.Core.Cloud
{
    public class Queue
    {
        public static void AddMessage(string message)
        {
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)); // Error and error message is "error"

                RoleEnvironment.Changed += (sender, arg) =>
                {
                    if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
                      .Any((change) => (change.ConfigurationSettingName == configName)))
                    {
                        if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
                        {
                            RoleEnvironment.RequestRecycle();
                        }
                    }
                };
            });
                   
            //adding message to the queue for the worker role to finish processing
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
            var queueClient = storageAccount.CreateCloudQueueClient();
            var queue = queueClient.GetQueueReference("wassupqueue");
            queue.CreateIfNotExist();
            var msg = new CloudQueueMessage(message); //asking the worker to refresh likes :)
            queue.AddMessage(msg);
        }

        public static void GetCompatibility(int p)
        {
            Core.Cloud.Queue.AddMessage("Compatibility:" + p);
        }

        public static void AddTrophyRefreshTextToCloudQueue(int userId)
        {
            Core.Cloud.Queue.AddMessage("Trophy:" + userId);
        }

        public static void AddCloudHangoutInsertedMessage(int userId, int hangoutId)
        {
            Cloud.Queue.AddMessage("HangoutAdded:" + hangoutId + ":User:" + userId);
        }

        public static void RefreshFacebookLikes(int userId)
        {
            Core.Cloud.Queue.AddMessage("RefreshLikes:" + userId);
        }
        
    }
}